<?php

/**
 * Returns the HTML display of multiple entities (in this case, entities of subtype Ã¢â‚¬ËœimageÃ¢â‚¬â„¢).
 * The name should be changed to Ã¢â‚¬Ëœdisplay_latest_whiteboarddrawingsÃ¢â‚¬â„¢ in the next commit.
 * 
 * @param int $num_images - Total number of images we want to display (not number of images in each page of pagination)
 * @param int $owner_guid - The owner GUID of the images we want to display
 * @return string - The HTML display code
 */
function greengar_list_latest_drawings($num_images, $owner_guid = 0) {
    $prev_context = set_context('front');

    $options = array(
        'metadata_names' => WHITEBOARD_DRAWING_METADATA,
        'metadata_values' => 1,
        'types' => 'object',
        'subtypes' => WHITEBOARD_DRAWING_SUBTYPE,
        'owner_guids' => $owner_guid,
        'limit' => 50
    );
    $entities = elgg_get_entities_from_metadata($options);
    greengar_filter_hidden_drawings($entities);

    $count = count($entities);
    $img_to_disp = array_slice($entities, 0, $num_images);
    $image_html = elgg_view_entity_list($img_to_disp, $count, 0, $num_images, false, false, false);

    set_context($prev_context);
    return $image_html;
}

function greengar_list_highestrated_drawings($num_images, $owner_guid = 0) {
    $entities = greengar_get_highestrated_thismonth($owner_guid, 50);
    greengar_filter_hidden_drawings($entities);
    
    $count = count($entities);
    $img_to_disp = array_slice($entities, 0, $num_images);

    $prev_context = set_context('front');
    $image_html = elgg_view_entity_list($img_to_disp, $count, 0, $num_images, false, false, false);
    set_context($prev_context);
    return $image_html;
}

/**
 * Return a direct url of a thumbnail of an image
 * 
 * @param int $guid - The GUID of the image we want to get thumbnail link
 * @param string $thumbnail_type - Must be 'largethumb', 'smallthumb' or 'thumb'
 * @return string - The direct url of the thumbnail image
 */
function greengar_get_thumbnail_link($guid, $thumbnail_type = 'thumb') {
    if (strcmp($thumbnail_type, 'largethumb') != 0 && strcmp($thumbnail_type, 'smallthumb') != 0 && strcmp($thumbnail_type, 'thumb') != 0)
        return '';

    $file = new ElggFile($guid);
    $filename_arr = explode('/', $file->getFilenameOnFilestore());
    $last_part = $thumbnail_type . array_pop($filename_arr);
    $thumb_filename_on_disk = implode('/', $filename_arr) . '/' . $last_part;

    return greengar_path_to_url($thumb_filename_on_disk);
}

/**
 * Receive a file path and return the http url equivalent
 * 
 * @global object $CONFIG
 * @param string $path - The path on disk of a file
 * @return string - The direct url of the file
 */
function greengar_path_to_url($path) {
    global $CONFIG;

    // Split Elgg's dataroot & wwwroot
    $dataroot_arr = explode('/', $CONFIG->dataroot);
    $wwwroot_arr = explode('/', $CONFIG->wwwroot);

    // Get the parts we need
    array_pop($dataroot_arr);
    array_pop($dataroot_arr);
    array_pop($wwwroot_arr);
    array_pop($wwwroot_arr);

    // Glue them together
    $new_dataroot = implode('/', $dataroot_arr);
    $new_wwwroot = implode('/', $wwwroot_arr);

    // Replace and return
    return str_replace($new_dataroot, $new_wwwroot, $path);
}

function greengar_add_tabmenu_item($label, $link, $group = 'a', $onclick = false, $selected = NULL) {
    global $CONFIG;

    if (!isset($CONFIG->wb_tabmenu)) {
        $CONFIG->wb_tabmenu = array();
    }
    if (!isset($CONFIG->wb_tabmenu[$group])) {
        $CONFIG->wb_tabmenu[$group] = array();
    }

    $item = new stdClass;
    $item->value = $link;
    $item->name = $label;
    $item->onclick = $onclick;
    $item->selected = $selected;
    $CONFIG->wb_tabmenu[$group][] = $item;
}

function greengar_get_tabmenu() {
    $submenu_total = "";
    global $CONFIG;

    if (isset($CONFIG->wb_tabmenu) && $submenu_register = $CONFIG->wb_tabmenu) {
        ksort($submenu_register);
        $selected_key = NULL;
        $selected_group = NULL;

        foreach ($submenu_register as $groupname => $submenu_register_group) {
            $submenu = "";

            foreach ($submenu_register_group as $key => $item) {
                $selected = false;
                // figure out the selected item if required
                // if null, try to figure out what should be selected.
                // warning: Fuzzy logic.
                if (!$selected_key && !$selected_group) {
                    if ($item->selected === NULL) {
                        $uri_info = parse_url($_SERVER['REQUEST_URI']);
                        $item_info = parse_url($item->value);

                        // don't want to mangle already encoded queries but want to
                        // make sure we're comparing encoded to encoded.
                        // for the record, queries *should* be encoded
                        $uri_params = array();
                        $item_params = array();
                        if (isset($uri_info['query'])) {
                            $uri_info['query'] = html_entity_decode($uri_info['query']);
                            $uri_params = elgg_parse_str($uri_info['query']);
                        }
                        if (isset($item_info['query'])) {
                            $item_info['query'] = html_entity_decode($item_info['query']);
                            $item_params = elgg_parse_str($item_info['query']);
                        }

                        $uri_info['path'] = trim($uri_info['path'], '/');
                        $item_info['path'] = trim($item_info['path'], '/');

                        // only if we're on the same path
                        // can't check server because sometimes it's not set in REQUEST_URI
                        if ($uri_info['path'] == $item_info['path']) {

                            // if no query terms, we have a match
                            if (!isset($uri_info['query']) && !isset($item_info['query'])) {
                                $selected_key = $key;
                                $selected_group = $groupname;
                                $selected = TRUE;
                            } else {
                                if ($uri_info['query'] == $item_info['query']) {
                                    $selected_key = $key;
                                    $selected_group = $groupname;
                                    $selected = TRUE;
                                } elseif (!count(array_diff($uri_params, $item_params))) {
                                    $selected_key = $key;
                                    $selected_group = $groupname;
                                    $selected = TRUE;
                                }
                            }
                        }
                        // if TRUE or FALSE, set selected to this item.
                        // Group doesn't seem to have anything to do with selected?
                    } else {
                        $selected = $item->selected;
                        $selected_key = $key;
                        $selected_group = $groupname;
                    }
                }

                $submenu .= elgg_view('canvas_header/wb_tabmenu_template', array(
                    'href' => $item->value,
                    'label' => $item->name,
                    'onclick' => $item->onclick,
                    'selected' => $selected,
                        ));
            }

            $submenu_total .= elgg_view('canvas_header/wb_tabmenu_group', array(
                'submenu' => $submenu,
                'group_name' => $groupname
                    ));
        }
    }

    return $submenu_total;
}

function greengar_custom_index($hook, $type, $return, $params) {
    global $CONFIG;

    if (!include_once($CONFIG->pluginspath . WHITEBOARD_PLUGIN_DIR . "/index.php")) {
        return false;
    }

    // return true to signify that we have handled the front page
    return true;
}

function greengar_get_highestrated_thismonth($ownerid = 0, $limit = 10)
{
    global $CONFIG;
    $dbprefix = $CONFIG->dbprefix;
    
    $sql = 'select e.guid from '.$dbprefix.'entities e
        join '.$dbprefix.'entity_subtypes sub on e.subtype=sub.id and sub.subtype=\''.WHITEBOARD_DRAWING_SUBTYPE.'\'
        join '.$dbprefix.'metadata m on e.guid=m.entity_guid
        join '.$dbprefix.'metastrings ms on m.name_id=ms.id and ms.string=\'avg_rating\'
            join '.$dbprefix.'metastrings ms2 on m.value_id=ms2.id
            order by ms2.string desc
            limit '.$limit;
    $result = get_data($sql);
    
    $entities = array();
    foreach ($result as $r)
        array_push($entities, get_entity($r->guid));
    return $entities;
}

function greengar_ratebox($hook, $entity_type, $returnvalue, $params) {
    echo '<input id="rate' . $params['guid'] . '-avg" type="hidden" value="' . $params['avg'] . '" />
            <div id="rate' . $params['guid'] . '"></div>
                <script type="text/javascript">
                startRaty(' . $params['guid'] . ');
                </script>';
    return true;
}

function greengar_filter_hidden_drawings(&$images) {
    $viewing_userid = get_loggedin_userid();
    $count = count($images);

    foreach ($images as $k => $i) {
        if ($i->is_hidden == 1
                && (is_array($i->reporters) && in_array($viewing_userid, $i->reporters)
                || ($viewing_userid === $i->reporters))) {
            for ($j = $k; $j < ($count - 1); ++$j)
                $images[$j] = $images[$j + 1];
            array_pop($images);
            --$count;
        }
    }
}